package com.xiaoyu.izf.util;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

public class SslHttpUtils {

    private static final int timeOut=9000;
    private static final Logger logger      = LoggerFactory.getLogger(SslHttpUtils.class);

    public static String sendGet(String url){
        return sendGet(url,null);
    }

    public static String sendGet(String url, Map<String, String> parameters) {
        String result = "";
        StringBuffer sb = new StringBuffer();// 存储参数
        String params = "";// 编码之后的参数
        try {
            String full_url = url;
            if(parameters!=null) {
                if (parameters.size() == 1) {
                    for (String name : parameters.keySet()) {
                        sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name), "UTF-8"));
                    }
                    params = sb.toString();
                } else {
                    for (String name : parameters.keySet()) {
                        sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name), "UTF-8")).append("&");
                    }
                    String temp_params = sb.toString();
                    params = temp_params.substring(0, temp_params.length() - 1);
                }
                full_url = url + "?" + params;
            }
            URL connURL = new URL(full_url);
            if("https".equalsIgnoreCase(connURL.getProtocol())){
                SslUtils.ignoreSsl();
            }
            URLConnection conn  = connURL.openConnection();
            conn.setConnectTimeout(timeOut);
            conn.setReadTimeout(timeOut);
            return IOUtils.toString(conn.getInputStream(),"utf-8");
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
        }
        return result;
    }

    /**
     * 发送POST请求
     *
     * @param url        目的地址
     * @param parameters 请求参数，Map类型。
     * @return 远程响应结果
     */
    public static String sendPost(String url, Map<String, String> parameters) {
        String result = "";// 返回的结果
        PrintWriter out = null;
        StringBuffer sb = new StringBuffer();// 处理请求参数
        String params = "";// 编码之后的参数
        try {
            // 编码请求参数
            if (parameters.size() == 1) {
                for (String name : parameters.keySet()) {sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name),"UTF-8"));
                }
                params = sb.toString();
            } else {
                for (String name : parameters.keySet()) {sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name),"UTF-8")).append("&");
                }
                String temp_params = sb.toString();
                params = temp_params.substring(0, temp_params.length() - 1);
            }
            // 创建URL对象
            URL connURL = new URL(url);
            if("https".equalsIgnoreCase(connURL.getProtocol())){
                SslUtils.ignoreSsl();
            }
            // 打开URL连接
            URLConnection httpConn = connURL.openConnection();
            // 设置POST方式
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            // 获取HttpURLConnection对象对应的输出流
            out = new PrintWriter(httpConn.getOutputStream());
            // 发送请求参数
            out.write(params);
            // flush输出流的缓冲
            out.flush();
            httpConn.getOutputStream();
            return IOUtils.toString(httpConn.getInputStream(),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String httpSend(String url,String params,String appid) {
        System.out.println("111111111:"+url);
        String result = "";// 返回的结果
        PrintWriter out = null;
        StringBuffer sb = new StringBuffer();// 处理请求参数
        try {
            // 创建URL对象
            URL connURL = new URL(url);
            if("https".equalsIgnoreCase(connURL.getProtocol())){
                SslUtils.ignoreSsl();
            }
            // 打开URL连接
            URLConnection httpConn = connURL.openConnection();
            // 设置POST方式
            httpConn.setRequestProperty("X-MBX-APIKEY",appid);
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            // 获取HttpURLConnection对象对应的输出流
            out = new PrintWriter(httpConn.getOutputStream());
            // 发送请求参数
            out.write(params);
            // flush输出流的缓冲
            out.flush();
            httpConn.getOutputStream();
            return IOUtils.toString(httpConn.getInputStream(),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public String getRequest(String url,int timeOut) throws Exception{
        URL u = new URL(url);
        if("https".equalsIgnoreCase(u.getProtocol())){
            SslUtils.ignoreSsl();
        }
        URLConnection conn = u.openConnection();
        conn.setConnectTimeout(timeOut);
        conn.setReadTimeout(timeOut);
        return IOUtils.toString(conn.getInputStream(),"utf-8");
    }
}
